package com.xuecheng.content.controller;

import com.xuecheng.api.content.FileApi;
import com.xuecheng.api.content.model.file.UploadTokenResult;
import com.xuecheng.content.common.constant.ContentErrorCode;
import com.xuecheng.content.common.exception.ExceptionCast;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
public class FileController implements FileApi {

    //远程调用文件服务系统
    @Autowired
    private RestTemplate restTemplate;
    //配置文件
    //加载nacos的配置文件内容（这里是内容管理的）
    @Value("${file.service.url}")
    private String url;
    @Value("${file.service.bucket}")
    private String bucket;
    @Value("${file.service.upload.region}")
    private String region;
    @Value("${cdn.domain}")
    private String domain;
    @Value("${file.token.type}")
    private String type;
    @Value("${file.token.deadline}")
    private int deadline;

    @Override
    @GetMapping("common/qnUploadToken")
    public UploadTokenResult qiniuUploadToken() {

        HashMap<String, Object> requestBody = new HashMap<>();
        requestBody.put("tokenType", type);
        requestBody.put("scope", bucket);
        requestBody.put("deadline", deadline);

        // 上传文件的key：唯一
        String fileKey = UUID.randomUUID().toString() + RandomStringUtils.randomAlphanumeric(16);
        requestBody.put("key", fileKey);

        //远程调用像文件系统发送请求
        ResponseEntity<Map> responseEntity = restTemplate.postForEntity(url, requestBody, Map.class);

        //获取code的值
        int statusCodeValue = responseEntity.getStatusCodeValue();
        //判断cods值是否等于200
        if (!(HttpStatus.OK.value() == statusCodeValue)){
            ExceptionCast.cast(ContentErrorCode.E_120602);
        }
        //获取响应结果
        Map body = responseEntity.getBody();
        // 2.将结果封装成前端所需要的内容并返回
        UploadTokenResult tokenResult = new UploadTokenResult();

        tokenResult.setTokenType(type);
        tokenResult.setScope(bucket);
        tokenResult.setKey(fileKey);
        tokenResult.setQnToken(body.get("result").toString());
        tokenResult.setUp_region(region);
        tokenResult.setDomain(domain);
        tokenResult.setDeadline(deadline);

        return tokenResult;

    }
}
